import { Module } from 'vuex'
import router from '@/router'

import type { IAccount } from '@/service/login/type'
import { mapMenuToRoutes, mapMenusToPermission } from '@/utils/map-menus'
import {
  accountLoginRequest,
  registerRequest,
  requestUserInfoById,
  requestUserMenuByRoleId,
  reqShopInfo
} from '@/service/login/login'

import localCache from '@/utils/cache'

//Module需要两个泛型 一个为模块内state的类型 一个为根模块类型
import { ILoginState } from './types'
import { IRootState } from '../types'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenu: [],
      permissions: []
    }
  },
  mutations: {
    changeToken(state, payload: string) {
      state.token = payload
    },
    changeUserInfo(state, payload: any) {
      state.userInfo = payload
    },
    changeUserMenu(state, payload: any) {
      state.userMenu = payload
      //userMenu 映射到 routes
      const routes = mapMenuToRoutes(payload)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      //获取用户按钮权限
      state.permissions = mapMenusToPermission(payload)
    }
  },
  actions: {
    //实现登录
    async accountLoginAction(context, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)
      console.log(loginResult)
      const { id, token } = loginResult
      context.commit('changeToken', token)
      localCache.setCache('token', token)
      //发送初始请求 完整department role
      //context.dispatch('getInitialDataAction', null, { root: true })
      //请求用户信息
      const userInfo = await requestUserInfoById(id)
      console.log(userInfo)

      if (userInfo.method == 1) {
        const info = await reqShopInfo(userInfo.id)
        localCache.setCache(`shop_id`, info[0].id)
      }
      context.commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)
      //请求用户菜单
      const userMenuResult = await requestUserMenuByRoleId(userInfo.id)
      const userMenus = userMenuResult
      context.commit('changeUserMenu', userMenus)
      localCache.setCache('userMenus', userMenus)
      //跳转到首页
      router.push('/main')
    },
    loadLocalLogin(context) {
      const token = localCache.getCache('token')
      if (token) {
        context.commit('changeToken', token)
        context.dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        context.commit('changeUserInfo', userInfo)
      }
      const userMenu = localCache.getCache('userMenus')
      if (userMenu) {
        context.commit('changeUserMenu', userMenu)
      }
    },
    async registerReq(context, payload: IAccount) {
      const res = await registerRequest(payload)
      return 1
    }
  }
}
export default loginModule
